from apps.common.base.dao import BaseDao
from apps.system.user.serializers import *
from django.db.models import F, Q
from apps.system.rank.dao import RankDao
import datetime
from decimal import Decimal
from apps.common.utils.tools import random_str, random_uuid
from apps.common.extension.customException import *
from apps.system.role.dao import RoleDao

class UserDao(BaseDao):
    MODEL_CLASS = UserModel
    SERI_CLASS = UserBaseSerializer

    def create(self, data):
        try:
            # 校验用户的手机号不能重复
            role = RoleDao().findOneByFilters({'key': 'custom'})
            if not role:
                raise VerifyException('角色不存在')
            if role.types == 'user':
                if data.get('phone'):
                    if UserDao().findAll().filter(phone=data.get('phone')).count() > 0:
                        raise VerifyException('手机号已存在')
            return super().create(data)
        except Exception as e:
            raise e
    
    def update(self, obj_id, data):
        try:
            # 校验用户的手机号不能重复
            user = UserDao().findOneByObjId(obj_id)
            if user.role.key =='custom' and data.get('phone'):
                if UserDao().findAll().filter(phone=data.get('phone')).exclude(id=obj_id).count() > 0:
                    raise VerifyException('手机号已存在')
            # 重写内容
            if data.get('rank'):
                rank = RankDao().findOneByObjId(data.get('rank'))
                if rank.grade == 2:
                    data['upRankTime'] = str(datetime.datetime.now())
            self.checkParentRank(user)
            return super().update(obj_id, data)
        except Exception as e:
            raise e

    def delete(self, obj_ids, data={}):
        try:
            for user in UserDao().findAll().filter(id__in=obj_ids):
                user.username = random_str(4) + user.username
                user.save()
            # 调用父类的 delete 方法
            user_instance = super().delete(obj_ids, data)
            return user_instance
        except Exception as e:
            raise e
        
    # def findAllUser(self):
    #     _list = UserDao().findAll().filter(role__types='user')
    #     _list = _list.select_related('parent', 'rank', 'role', 'team', 'identity').prefetch_related('user_ActivityPerformance')
    #     return _list
    
    # def findAllUserByLessee(self, lessee):
    #     _list = self.findAllUser().filter(lessee=lessee)
    #     return _list

    # def findAllAdmin(self):
    #     _list = UserDao().findAll().filter(role__types='admin')
    #     _list = _list.select_related('role')
    #     return _list
    # def findAllAdminByLessee(self, lessee):
    #     _list = self.getAllAdmin(self).filter(lessee=lessee)
    #     return _list

    # 查单个实例
    def findOneByObjCode(self, obj_code):
        try:
            objs = self.findAllUser().filter(code=obj_code)
            if objs.exists():
                return objs[0]
            else:
                return False
        except self.MODEL_CLASS.DoesNotExist:
            print(self.MODEL_CLASS, obj_code, '记录不存在')
            return False

    def addWallet(self, scene, obj, value):
        # print('增加积分', scene, obj, value)
        value = Decimal(value).quantize(Decimal("0.00"))
        if value == 0:
            return
        value = value.quantize(Decimal("0.00"))
        if scene == 'incomes':
            obj = UserModel.objects.get(id=obj.id)
            obj.incomes = F('incomes') + value
            obj.save()
        elif scene == 'incomesLocked':
            obj = UserModel.objects.get(id=obj.id)
            obj.incomesLocked = F('incomesLocked') + value
            obj.save()
        elif scene == 'historyIncomes':
            obj = UserModel.objects.get(id=obj.id)
            obj.historyIncomes = F('historyIncomes') + value
            obj.save()
        elif scene == 'balance':
            obj = UserModel.objects.get(id=obj.id)
            obj.balance = F('balance') + value
            obj.save()
        elif scene == 'contributionValue':
            obj = UserModel.objects.get(id=obj.id)
            obj.contributionValue = F('contributionValue') + value
            obj.save()
        elif scene == 'incomesOriginal':
            obj = UserModel.objects.get(id=obj.id)
            obj.incomesOriginal = F('incomesOriginal') + value
            obj.save()
        elif scene == 'incomesReduction':
            obj = UserModel.objects.get(id=obj.id)
            obj.incomesReduction = F('incomesReduction') + value
            obj.save()
        elif scene == 'cashSellingMoney':
            obj = UserModel.objects.get(id=obj.id)
            obj.cashSellingMoney = F('cashSellingMoney') + value
            obj.save()
        elif scene == 'shop_balance':
            obj = UserModel.objects.get(id=obj.id)
            obj.shop_balance = F('shop_balance') + value
            obj.save()
        else:
            print('payway不存在')

    def subWallet(self, scene, obj, value):
        print('减少积分', scene, obj, value)
        value = Decimal(value).quantize(Decimal("0.00"))
        if value == 0:
            return
        if scene == 'incomes':
            obj = UserModel.objects.get(id=obj.id)
            obj.incomes = F('incomes') - value
            obj.save()
        elif scene == 'incomesLocked':
            obj = UserModel.objects.get(id=obj.id)
            obj.incomesLocked = F('incomesLocked') - value
            obj.save()
        elif scene == 'historyIncomes':
            obj = UserModel.objects.get(id=obj.id)
            obj.historyIncomes = F('historyIncomes') - value
            obj.save()
        elif scene == 'balance':
            obj = UserModel.objects.get(id=obj.id)
            obj.balance = F('balance') - value
            obj.save()
        elif scene == 'contributionValue':
            obj = UserModel.objects.get(id=obj.id)
            obj.contributionValue = F('contributionValue') - value
            obj.save()
        elif scene == 'incomesOriginal':
            obj = UserModel.objects.get(id=obj.id)
            obj.incomesOriginal = F('incomesOriginal') - value
            obj.save()
        elif scene == 'incomesReduction':
            obj = UserModel.objects.get(id=obj.id)
            obj.incomesReduction = F('incomesReduction') - value
            obj.save()
        elif scene == 'cashSellingMoney':
            obj = UserModel.objects.get(id=obj.id)
            obj.cashSellingMoney = F('cashSellingMoney') - value
            obj.save()
        elif scene == 'shop_balance':
            obj = UserModel.objects.get(id=obj.id)
            obj.shop_balance = F('shop_balance') - value
            obj.save()
        else:
            print('payway不存在')
            
    def addRank(self, user, grade):
        if user.rank.grade < grade:
            user = UserModel.objects.get(id=user.id)
            user.rank = RankDao().findOneByGrade(grade)
            user.save()

    def checkParentRank(self, user):
        try:
            if user and user.id:
                if user.parent is None:
                    return True
                # if user.parent.rank.grade == 0: # 粉丝不升级
                #     return True
                limit = 2
                level = 2
                _parent = UserModel.objects.get(id=user.parent.id)
                if UserDao().findAll().filter(parent=_parent, rank__grade__gte=1).count()>=limit:
                    if _parent.rank.grade < level:
                        UserDao().update(_parent.id, {'rank': RankDao().findOneByGrade(level).id, "upRankTime": datetime.datetime.now()})
                
                if user.parent:
                    self.checkParentRank(user.parent)
            else:
                return False
        except Exception as e:
            print(e)
            return False
